package com.uyaer.engine.core
{
	import com.uyaer.engine.event.EventManager;
	import com.uyaer.engine.event.EventType;
	
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	public class Tick
	{
		private var timer:Timer;
		public var fps:int = 0; 
		private var timeDelay:int = 33;
		private var time:Number;
		private var sec:Number; //秒时间点
		
		private var refreshFun:Array = new Array();
		public function Tick()
		{
			timer = new Timer(timeDelay);
			timer.addEventListener(TimerEvent.TIMER,_timerHandler);
			timer.start();
			time = new Date().time;
			sec = time;
		}
		
		private function _timerHandler(e:TimerEvent):void{
			var now:Number = new Date().time;
			if((now - time) > timeDelay){
				tick();
				time = now;
			}
			fps ++;
			if(now - sec > 1000){
				EventManager.dispatchEvent(EventType.ASECOND);
				sec = now;
				fps = 0 ;
			}
		}
		
		/**
		 *每一帧进行的刷新 
		 */		
		private function tick():void{
			for(var i:int = 0 ; i < refreshFun.length ; i ++){
				refreshFun[i]();
			}
			var second:Number = new Date().time;
		}
		
		public function addRefresh(fun:Function):void{
			refreshFun.push(fun);
		}
		
		public function removeRefresh(fun:Function):void{
			var index:int = refreshFun.indexOf(fun);
			if(index > -1){
				refreshFun.splice(index , 1);
			}
		}
	}
}